// FootballGadget class extends Gadget class
	FootballGadget.prototype=new Gadget();
	
	// FootballGadget class
	function FootballGadget() {
		
		//////////////////////////////////////
		//////////////////////////////////////
		// When DOM is ready init gadget
		//
		this.onLoaded=function(){
			// Subscribe to onresize event
			this.subscribeToOnresize();
			// Init Country and League select boxes
			this.initCountrySelect();
			// Init tabs
			this.initTabs();
			// Fire handler for league selected
			this.onLeagueSelected();
		};
		//////////////////////////////////////
		
		
		//////////////////////////////////////
		//////////////////////////////////////
		// Display error message
		// - requires message bundles
		//
		this.onError=function(errorCode) {
			var errorMessage=this.getPref("msg","error_"+errorCode);
			// If we are automatically doing something
			// about the error then show what
			if(errorCode=="08"){
				this.addClassNameTo("msgError","withWhatAreWeDoing");
				errorMessage=errorMessage.replace(/\. (.+)$/,"<span id='whatWeAreDoingAboutIt'>$1</span>");
			}
			else
				this.removeClassNameFrom("msgError","withWhatAreWeDoing");
			this.insertHTML("msgError",errorMessage);
			this.insertHTML("ctrMatchListing","");
			this.showError();
		};
		//////////////////////////////////////
		
		
		//////////////////////////////////////
		//////////////////////////////////////
		// Subscribe to resize event
		//
		this.subscribeToOnresize=function(){
			_self=this;
			if(window.onresize)
				_oldResize=window.onresize;
			window.onresize=function(){
				_self.onResize();
				if(typeof(oldResize)=="function") _oldResize();
			};
			_self.onResize();
		};
		this.onResize=function(){
			// Remove override formatting
			_gel("selMonth").style.width=null;
			// Check computed widths
			var lblWidth=_gel("lblMatchArchive").offsetWidth+10;
			var frmWidth=_gel("frmMatchArchive").offsetWidth+10;
			var ctrWidth=_gel("ctrMatchArchive").offsetWidth;
			if(ctrWidth<=lblWidth+frmWidth){
				this.addClassNameTo("lblMatchArchive","notEnoughSpaceForYou");
				this.addClassNameTo("frmMatchArchive","withLabelHidden");
				_gel("selMonth").style.width="0px";
				_gel("selMonth").style.width=(ctrWidth-25-_gel("clkSubmitMatchArchive").offsetWidth-_gel("ctrSelTeam").offsetWidth-_gel("selYear").offsetWidth)+"px";
			}
			else {
				this.removeClassNameFrom("lblMatchArchive","notEnoughSpaceForYou");
				this.removeClassNameFrom("frmMatchArchive","withLabelHidden");
			}
		};
		//////////////////////////////////////
		
		
		//////////////////////////////////////
		//////////////////////////////////////
		// Default/selected options
		// 
		this.selectedCountry=null;
		this.selectedLeague=null;
		this.selectedSex=null;
		this.selectedTab=null;
		this.setSelected=function(selectedOptions){
			if(selectedOptions.Country.indexOf("-")>-1){
				this.selectedCountry=selectedOptions.Country.split("-")[0];
				this.selectedCountryLabel=selectedOptions.Country.split("-")[1];
			}
			else {
				this.selectedCountry=selectedOptions.Country;
				if(selectedOptions.CountryLabel){
					if(selectedOptions.CountryLabel=="England" ||
						selectedOptions.CountryLabel=="Scotland" ||
						selectedOptions.CountryLabel=="Wales")
						this.selectedCountryLabel=this.Prefs.getMsg("Country_GB_"+selectedOptions.CountryLabel);
					else
						this.selectedCountryLabel=selectedOptions.CountryLabel;
				}
			}
			if(selectedOptions.League)
				this.selectedLeague=selectedOptions.League;
			else {
				for(var i=0; i<this.Countries.length; i++){
					if(this.Countries[i].id==this.selectedCountry){
						this.selectedLeague=this.Countries[i].defaultLeague;
						break;
					}
				}
			}
			this.selectedSex=selectedOptions.Sex.toLowerCase();
			this.selectedTab=selectedOptions.Tab;
			if(selectedOptions.MatchArchiveMonth)
				this.MatchArchiveMonth=selectedOptions.MatchArchiveMonth;
			if(selectedOptions.MatchArchiveYear)
				this.MatchArchiveYear=selectedOptions.MatchArchiveYear;
			if(selectedOptions.MatchArchiveTeamId)
				this.MatchArchiveTeamId=selectedOptions.MatchArchiveTeamId;
			if(selectedOptions.Season)
				this.selectedSeason=selectedOptions.Season;
			if(selectedOptions.NewsSearchQuery)
				this.NewsSearchQuery=selectedOptions.NewsSearchQuery;
		};
		this.setDefaults=function(userConfigObj){
			var noSavedState=this.loadSavedState();
			if(!noSavedState)
				this.setSelected(userConfigObj);
		};
		this.loadSavedState=function(){
			var savedState=this.getPref("string","saved_state");
			if(savedState!=""){
				savedState=savedState.split("|");
				this.setSelected({
					Country:savedState[0].split("-")[0],
					CountryLabel:savedState[0].split("-")[1],
					League:savedState[1],
					Sex:"__UP_male_female__",
					Tab:savedState[3],
					MatchArchiveMonth:savedState[4],
					MatchArchiveYear:savedState[5],
					MatchArchiveTeamId:savedState[6],
					Season:savedState[7],
					NewsSearchQuery:savedState[8]
				});
				return true;
			}
			return false;
		};
		this.saveState=function(){
			var selectedCountry=this.selectedCountry;
			if(selectedCountry.toLowerCase()=="gb"){
				var nameToMap=this.selCountryElem.options[this.selCountryElem.selectedIndex].text;
				for(var i=0; i<this.Countries.length; i++){
					if(this.Countries[i].id.toLowerCase()=="gb" &&
						this.Countries[i].name==nameToMap)
						var countryLbl=this.Countries[i].label;
				}
				if(countryLbl)
					selectedCountry=selectedCountry+"-"+countryLbl;
			}
			var stateArray=[
				selectedCountry,
				this.selectedLeague,
				this.selectedSex,
				this.selectedTab,
				"",
				"",
				"",
				this.selectedSeason,
				this.NewsSearchQuery
			];
			this.setPref("saved_state",stateArray.join("|"));
		};
		//////////////////////////////////////
		
		
		//////////////////////////////////////
		//////////////////////////////////////
		// Initialise functions
		//
		this.startGettingData=function(){
			// Start getting match data before
			// DOM is ready
			this.getMatchData();
		};
		this.onLeagueSelected=function(){
			// Get team and player names for
			// selected league
			this.getTeamNamesForLeague();
			// Reset match archive filter
			this.resetArchiveFilter();
			// Reset seasons filter
			this.resetSeasonsFilter();
			// Reset news search
			this.resetNewsFilter();
		};
		//////////////////////////////////////
		
		
		//////////////////////////////////////
		//////////////////////////////////////
		// Tab related functions
		//
		this.initTabs=function(){
			// Switch tab (with firstrun flag)
			this.switchTab(this.selectedTab,true);
			// Hide all tabs and show selected (default)
			this.toggleDisplay("ctrTabMatches","none");
			this.toggleDisplay("ctrMatchArchive","none");
			this.toggleDisplay("ctrTabStandings","none");
			this.toggleDisplay("ctrStandingsArchive","none");
			this.toggleDisplay("ctrTabNews","none");
			this.toggleDisplay("ctrNewsSearch","none");
			// Show default tab and filter
			this.toggleDisplay(this.selectedTab,"block");
			switch(this.selectedTab){
				case "ctrTabMatches":this.toggleDisplay("ctrMatchArchive","block");break;
				case "ctrTabStandings":this.toggleDisplay("ctrStandingsArchive","block");break;
				case "ctrTabNews":this.toggleDisplay("ctrNewsSearch","block");break;
			}
			// Tab onclick handlers
			_self=this;
			_gel("clkMatches").onclick=function(){_self.switchTab("ctrTabMatches")};
			_gel("clkLeague").onclick=function(){_self.switchTab("ctrTabStandings")};
			_gel("clkNews").onclick=function(){_self.switchTab("ctrTabNews")};
		};
		this.switchTab=function(tabToShow,firstRun){
			// Hide any errors
			this.hideError();
			// Unselect all tabs
			this.removeClassNameFrom("ctrClkMatches","selected");
			this.removeClassNameFrom("ctrClkLeague","selected");
			this.removeClassNameFrom("ctrClkNews","selected");
			// Load data for selected tab
			switch(tabToShow){
				case "ctrTabMatches":
					this.hideMatchDetail();
					if(_gel("ctrMatchListing").innerHTML==""){
						this.showLoaderFor("ctrMatchListing");
						if(firstRun) this.initMatchTab();
						else this.resetMatchTab();
					}
					this.onResize();
					var ctrClkElem="ctrClkMatches";
				break;
				case "ctrTabStandings":
					if(!this.CurrentSeason && !firstRun){
						this.onError("01");
					}
					else if(_gel("ctrStandingsTable").innerHTML==""){
						this.showLoaderFor("ctrStandingsTable");
						this.getLeagueStandingsWhenReady();
					}
					var ctrClkElem="ctrClkLeague";
				break;
				case "ctrTabNews":
					if(_gel("ctrNews").innerHTML==""){
						this.showLoaderFor("ctrNews");
						this.getNewsResults();
					}
					var ctrClkElem="ctrClkNews";
				break;
				default:
					throw new Error("Cannot recognise tab ID");
			}
			// Select selected tab
			this.addClassNameTo(ctrClkElem,"selected");
			// Toggle tab contents
			this.toggleDisplay("ctrTabMatches","none");
			this.toggleDisplay("ctrMatchArchive","none");
			this.toggleDisplay("ctrMatchDetailBack","none");
			this.toggleDisplay("ctrTabStandings","none");
			this.toggleDisplay("ctrStandingsArchive","none");
			this.toggleDisplay("ctrTabNews","none");
			this.toggleDisplay("ctrNewsSearch","none");
			this.toggleDisplay(tabToShow,"block");
			switch(tabToShow){
				case "ctrTabMatches":this.toggleDisplay("ctrMatchArchive","block");break;
				case "ctrTabStandings":this.toggleDisplay("ctrStandingsArchive","block");break;
				case "ctrTabNews":this.toggleDisplay("ctrNewsSearch","block");break;
			}
			// Save state
			this.selectedTab=tabToShow;
			if(!firstRun) this.saveState();
		};
		//////////////////////////////////////
		
		
		//////////////////////////////////////
		//////////////////////////////////////
		// Match data functions
		//
		this.MatchData=null;
		this.MatchListingReady=false;
		this.MatchDetailsReady=false;
		this.LiveMatchIds=[];
		this.MatchesLastModified=null;
		this.getLiveMatchData=function(){
			// Get matches being played today
			var url=this.getApiUrl("lastupdate",{type:"matches"});
			_self=this;
			this.fetchContent("xml",url,function(response){_self.handleLastModifiedHeader(response)},true,60);
		};
		this.handleLastModifiedHeader=function(response){
			var lastMod=this.MatchesLastModified;
			this.MatchesLastModified=new Date(response.lastModified);
			/*
			if(console && console.log){
				console.log("response: "+response)
				console.log("response.lastModified: "+response.lastModified)
				console.log("lastMod:"+lastMod+", this.MatchesLastModified:"+this.MatchesLastModified)
			}
			*/
			if(lastMod && lastMod!=this.MatchesLastModified){
				var fromDate=this.getApiFormattedDate();
				var toDate=fromDate;
				this.getMatchData(fromDate,toDate,null,null,60);
				this.hideError();
			}
		};
		this.getMatchData=function(fromDate,toDate,teamFilter,forceWriteFlag,cacheInt,holdTimeoutCheck){
			// Reset ready flag
			this.MatchListingReady=false;
			// If fromDate and toDate are not set then
			// get default time period: 7days (604,800,000ms)
			if(!fromDate && !toDate){
				var unformattedFromDate=new Date((new Date()).getTime()-604800000);
				var fromDate=this.getApiFormattedDate(unformattedFromDate);
				var toDate=this.getApiFormattedDate();
				this.CurrentListingTimeBoundary={
					upper:(new Date()).getTime()+unformattedFromDate.getTimezoneOffset()*60000,
					lower:(new Date((new Date()).getTime()-604800000)).getTime()+unformattedFromDate.getTimezoneOffset()*60000
				};
			}
			if(!teamFilter) var teamFilter=null;
			var paramsList={
				league_id:this.selectedLeague,
				country:this.selectedCountry,
				from_date:fromDate,
				to_date:toDate
			}
			if(teamFilter){
				// If teamFilter is set then we need to make
				// 2x API calls - for team_home and team_visit
				paramsList.team_home=teamFilter;
				var url=this.getApiUrl("matches",paramsList);
				_self=this;
				this.fetchContent(
					"xml",url,
					function(response){
						// Save part one of response
						_self.MatchData=[response];
						// Remove team_home param
						delete paramsList.team_home;
						// Add team_visit param
						paramsList.team_visit=teamFilter;
						var url=_self.getApiUrl("matches",paramsList);
						_self.fetchContent("xml",url,function(response){_self.handleMatchesData(response,"listing",true,forceWriteFlag)});
					}
				);
			}
			else {
				// If teamFilter is not set make single call
				var url=this.getApiUrl("matches",paramsList);
				_self=this;
				if(cacheInt)
					this.fetchContent("xml",url,function(response){_self.handleMatchesData(response,"live",false,forceWriteFlag,true)},!holdTimeoutCheck,cacheInt);
				else
					this.fetchContent("xml",url,function(response){_self.handleMatchesData(response,"listing",false,forceWriteFlag,false)},!holdTimeoutCheck);
			}
		};
		this.handleMatchesData=function(response,mode,concatResponseFlag,forceWriteFlag,liveData){
			// If response they we have just requested
			// data, if not then we are returning to
			// extract match detail data
			if(response){
				// If concatResponseFlag then add response
				// to existing saved response
				if(concatResponseFlag) this.MatchData[1]=response;
				else this.MatchData=[response];
				if(mode=="listing"){
					// Clear matches object
					this.Matches={};
				}
				else {
					// Clear live matches object
					this.LiveMatches={};
				}
			}
			// Force XML looping to only look for nodes required
			var listingNodeSet=["id","team_home","team_home_name","team_visit","team_visit_name","full_score","half_score","startdate","season_id","status_id","match_goals"];
			var detailNodeSet=["startdate","id","match_cards","match_substitutions","venue_name","spectator","elapsed_min"];
			if(mode=="listing"){
				var nodeSet=listingNodeSet;
			}
			else if(mode=="detail"){
				//var nodeSet=detailNodeSet;
				var nodeSet=listingNodeSet.concat(detailNodeSet);
			}
			else if(mode=="live"){
				var nodeSet=listingNodeSet.concat(detailNodeSet);
			}
			// For each data set, get all match nodes
			for(var h=0; h<this.MatchData.length; h++){
				var matchNodes=this.MatchData[h].getElementsByTagName("match");
				// Check for match nodes
				for(var i=0; i<matchNodes.length; i++){
					// For each match node, get child nodes
					var matchDataNodes=matchNodes.item(i).childNodes;
					// Reset saved obj properties and counter
					var savedProperties={};
					var nodeCounter=0;
					for(var j=0; j<matchDataNodes.length; j++){
						var matchDataNode=matchDataNodes.item(j);
						for(var k=0; k<nodeSet.length; k++){
							if(matchDataNode.nodeName==nodeSet[k]){
								// Handle special nodes
								if(nodeSet[k]=="status_id"){
									// Define score string from match status
									switch(matchDataNode.firstChild.nodeValue){
										case "1":
											savedProperties["full_score"]="v";
										break;
									}
								}
								else if(nodeSet[k]=="match_goals" || nodeSet[k]=="match_cards"){
									// Save booking or goal info
									savedProperties[nodeSet[k]]=[];
									var parElems=matchDataNode.getElementsByTagName(nodeSet[k].replace(/s$/,""));
									for(var l=0; l<parElems.length; l++){
										var minElem=parElems[l].getElementsByTagName("min").item(0);
										var min=(minElem.firstChild)? minElem.firstChild.nodeValue:"";
										var teamElem=parElems[l].getElementsByTagName("team_id").item(0);
										var team=(teamElem.firstChild)? teamElem.firstChild.nodeValue:"";
										var playerElem=parElems[l].getElementsByTagName("player_name").item(0);
										var player=(playerElem.firstChild)? playerElem.firstChild.nodeValue:"";
										var typeElem=parElems[l].getElementsByTagName("type").item(0);
										var type=(typeElem.firstChild)? typeElem.firstChild.nodeValue:"";
										savedProperties[nodeSet[k]].push({minute:min,team:team,player:player,type:type});
									}
								}
								else if(nodeSet[k]=="match_substitutions"){
									// Substitutions
									savedProperties["match_substitutions"]=[];
									var cards=matchDataNode.getElementsByTagName("match_substitution");
									for(var l=0; l<cards.length; l++){
										var minElem=cards[l].getElementsByTagName("min").item(0);
										var min=(minElem.firstChild)? minElem.firstChild.nodeValue:"";
										var teamElem=cards[l].getElementsByTagName("team_id").item(0);
										var team=(teamElem.firstChild)? teamElem.firstChild.nodeValue:"";
										var playerInElem=cards[l].getElementsByTagName("in_name").item(0);
										var playerIn=(playerInElem.firstChild)? playerInElem.firstChild.nodeValue:"";
										var playerOutElem=cards[l].getElementsByTagName("out_name").item(0);
										var playerOut=(playerOutElem.firstChild)? playerOutElem.firstChild.nodeValue:"";
										savedProperties["match_substitutions"].push({minute:min,team:team,player_in:playerIn,player_out:playerOut});
									}
								}
								// Capture property if not already defined
								if(!savedProperties[matchDataNode.nodeName])
									savedProperties[matchDataNode.nodeName]=(matchDataNode.firstChild)? matchDataNode.firstChild.nodeValue:"";
								nodeCounter++;
								break;
							}	
						}
						// If all the required nodes have been
						// found then break loop
						if(nodeCounter==nodeSet.length) break;
					}
					
					// Check date is within listing date bounds
					if(this.CurrentListingTimeBoundary){
						if(i===0){
							//console.log("Lower time boundary: "+(new Date(this.CurrentListingTimeBoundary.lower)));
							//console.log("Upper time boundary: "+(new Date(this.CurrentListingTimeBoundary.upper)));
						}
						var matchDateTime=this.getDateFromApiFormattedDate(savedProperties.startdate).getTime();
						if(matchDateTime<this.CurrentListingTimeBoundary.lower || matchDateTime>this.CurrentListingTimeBoundary.upper){
							if(i===matchNodes.length-1) this.CurrentListingTimeBoundary=null;
							continue;
						}
						else {
							if(i===matchNodes.length-1) this.CurrentListingTimeBoundary=null;
						}
					}
					
					/* "AFTER PENALTIES" SCORING CALCULATION
					if(savedProperties["full_score"] && savedProperties["match_goals"]){
						// Add goals to goal-types arrays
						var homeTeamId=savedProperties.team_home;
						savedProperties.split_score={
							TOTAL:savedProperties.full_score.split("-"),
							FT:[0,0],
							AET:[0,0],
							AP:[0,0]
						};
						for(var k=0; k<savedProperties.match_goals.length; k++){
							var thisGoal=savedProperties.match_goals[k];
							switch(thisGoal.type){
								case "11":
								case "12":
								case "13":
									if(thisGoal.team==homeTeamId){
										savedProperties.split_score.AET[0]++;
										savedProperties.split_score.TOTAL[0]--;
									}
									else {
										savedProperties.split_score.AET[1]++;
										savedProperties.split_score.TOTAL[1]--;
									}
								break;
								case "3":
								case "9":
								case "14":
								case "19":
									// Pen missed
									// Do nothing for now
								break;
								default:
									if(thisGoal.team==homeTeamId){
										savedProperties.split_score.FT[0]++;
										savedProperties.split_score.TOTAL[0]--;
									}
									else {
										savedProperties.split_score.FT[1]++;
										savedProperties.split_score.TOTAL[1]--;
									}
							}
						}
						for(var k=0; k<2; k++){
							savedProperties.split_score.AP[k]=savedProperties.split_score.TOTAL[k];
						}
						if((savedProperties.split_score.AET[0] || savedProperties.split_score.AET[1])!=0){
							savedProperties.status_id="AET";
							savedProperties.full_score=parseInt(savedProperties.split_score.FT[0]+savedProperties.split_score.AET[0])+"-"+parseInt(savedProperties.split_score.FT[1]+savedProperties.split_score.AET[1]);
						}
						if((savedProperties.split_score.AP[0] || savedProperties.split_score.AP[1])!=0){
							savedProperties.status_id="AET";
							savedProperties.full_score=parseInt(savedProperties.split_score.FT[0]+savedProperties.split_score.AET[0])+"-"+parseInt(savedProperties.split_score.FT[1]+savedProperties.split_score.AET[1]);
							var winningSide=(savedProperties.split_score.AP[0]>savedProperties.split_score.AP[1])? "home":"visit";
							if(winningSide=="home"){
								savedProperties.penalties_str=savedProperties.team_home_name+" __MSG_won__ <b>"+savedProperties.split_score.AP[0]+" - "+savedProperties.split_score.AP[1]+"</b> __MSG_after_penalties__";
							}
							else {
								savedProperties.penalties_str=savedProperties.team_visit_name+" __MSG_won__ <b>"+savedProperties.split_score.AP[1]+" - "+savedProperties.split_score.AP[0]+"</b> __MSG_after_penalties__";
							}
						}
					}
					*/
					
					// Remove time granularity from date grouping
					if(!savedProperties.startdate || !savedProperties.id){throw new Error("You need 'startdate' and 'id' in all nodeSet arrays!");break}
					var today=(new Date()).getTime();
					var dateOfGroup=this.getDateFromApiFormattedDate(savedProperties.startdate).getTime();
					if(dateOfGroup>today){
						// Future fixture
						//var sortByStartDate=savedProperties.startdate;
						//var sortByStartDate=this.getListingFormattedDate(this.getDateFromApiFormattedDate(savedProperties.startdate));
						var sortByStartDate=this.getDateFromApiFormattedDate(savedProperties.startdate).getTime();
					}
					else {
						// Past or in progress game
						//var sortByStartDate=savedProperties.startdate.replace(/ \d\d:\d\d:\d\d$/,"");
						//var sortByStartDate=this.getListingFormattedDate(this.getDateFromApiFormattedDate(savedProperties.startdate.replace(/ \d\d:\d\d:\d\d$/,"")));
						//var sortByStartDate=this.getDateFromApiFormattedDate(savedProperties.startdate.replace(/ \d\d:\d\d:\d\d$/,"")).getTime();
						var sortByStartDate=this.getDateFromApiFormattedDate(savedProperties.startdate,true).getTime();
					}
					//sortByStartDate=(new Date(sortByStartDate)).getTime();
					// Define objects if they don't exist
					if(mode=="live"){
						if(typeof(this.LiveMatches[sortByStartDate])!="object")
							this.LiveMatches[sortByStartDate]={};
						if(typeof(this.LiveMatches[sortByStartDate][savedProperties.id])!="object")
							this.LiveMatches[sortByStartDate][savedProperties.id]={};
					}
					else {
						if(typeof(this.Matches[sortByStartDate])!="object")
							this.Matches[sortByStartDate]={};
						if(typeof(this.Matches[sortByStartDate][savedProperties.id])!="object")
							this.Matches[sortByStartDate][savedProperties.id]={};
					}
					// Add each saved match property to matches object
					for(var property in savedProperties){
						if(mode=="live")
							this.LiveMatches[sortByStartDate][savedProperties.id][property]=savedProperties[property];
						else
							this.Matches[sortByStartDate][savedProperties.id][property]=savedProperties[property];
					}
					// Save current season if not already captured
					if(i==0 && h==0 && mode=="listing" && !this.CurrentSeason){
						this.CurrentSeason=savedProperties.season_id;
					}
				}
			}
			if(mode=="listing"){
				this.MatchListingReady=true;
				if(forceWriteFlag){
					this.writeMatchListingHtml();
				}
				// Go back to get match detail data
				this.handleMatchesData(null,"detail");
			}
			else if(mode=="detail"){
				this.MatchDetailsReady=true;
			}
			else if(mode=="live"){
				this.updateLiveMatchesHtml();
			}
		};
		this.searchForSeasonIdCounter=0;
		this.doErrorDelay=false;
		this.tryAgainToFindSeasonId=function(){
			// Only try 3 consequtive times
			if(this.searchForSeasonIdCounter++>2){
				this.searchForSeasonIdCounter=0;
				if(this.doErrorDelay){
					this.doErrorDelay=false;
					_self=this;
					setTimeout(function(){_self.onError("04")},1000);
				}
				else
					this.onError("04");
				return;
			}
			// If "this week" is selected get last
			// month results
			if(this.selMonthElem.selectedIndex==0){
				// 7 days ago
				var lastSearchDate=this.getApiFormattedDate(new Date((new Date()).getTime()-604800000));
				// Determine month and year
				var month=lastSearchDate.split("%20")[1];
				var year=lastSearchDate.split("%20")[2];
				// Loop thru month and year select
				for(var i=0; i<this.selMonthElem.options.length; i++){
					if(this.selMonthElem.options[i].text==month){
						this.selMonthElem.selectedIndex=i;
						break;
					}
				}
				for(var i=0; i<this.selYearElem.options.length; i++){
					if(this.selYearElem.options[i].text==year){
						this.selYearElem.selectedIndex=i;
						break;
					}
				}
			}
			else {
				// If jan then switch to dec and move year back
				if(this.selMonthElem.selectedIndex==2){
					if(this.selYearElem.selectedIndex!=this.selYearElem.options.length-1){
						this.selMonthElem.selectedIndex=this.selMonthElem.options.length-1;
						this.selYearElem.selectedIndex=this.selYearElem.selectedIndex+1;
					}
					else {
						this.onError("04");
						return;
					}
				}
				// Else just move month back
				else
					this.selMonthElem.selectedIndex=this.selMonthElem.selectedIndex-1;
			}
			// Init full month search
			this.handleMonthChange();
			this.handleMatchFilters(true);
			// Show user what we are doing
			this.onError("08");
			this.doErrorDelay=true;
		};
		// Called when DOM ready
		this.writeMatchListingWhenReady=function(){
			// Team names needed for display of results
			if(this.MatchListingReady && this.TeamNamesReady){
				this.writeMatchListingHtml();
			}
			else {
				_self=this;
				setTimeout(function(){_self.writeMatchListingWhenReady()},500);
			}
		};
		// Write HTML for match listing
		this.writeMatchListingHtml=function(){
			var matchListingElem=_gel("ctrMatchListing");
			// Stop any live updates
			this.stopLiveMatchUpdates();
			// Empty old HTML
			matchListingElem.innerHTML="";
			// Hide loader
			this.hideLoaderFor("ctrMatchListing");
			// Create array to order date groups
			var orderedDateGroups=[];
			for(var dateGroup in this.Matches){
				orderedDateGroups.push({dateGroup:dateGroup,matches:this.Matches[dateGroup]});
			}
			// If no match listings then show
			// error and try again to find
			// current season ID
			if(orderedDateGroups.length===0 && !this.currentSeason){
				this.tryAgainToFindSeasonId();
				return;
			}
			else {
				this.hideError();
			}
			// Sort groups into date order
			orderedDateGroups.sort(function(a,b){
					var x=parseInt(b.dateGroup);
					var y=parseInt(a.dateGroup);
					return ((x<y)? -1:((x>y)? 1:0));
			});
			// UL container elem for list of matches
			var ulNode=document.createElement("ul");
			for(var i=0; i<orderedDateGroups.length; i++){
				// LI for each date group
				var groupedByDate=parseInt(orderedDateGroups[i].dateGroup);
				var liDateGroup=document.createElement("li");
				liDateGroup.className="date-group-label";
				liDateGroup.innerHTML=this.getListingFormattedDate(new Date(groupedByDate));
				ulNode.appendChild(liDateGroup);
				// LI to hold each TABLE of matches
				liMatchesContainer=document.createElement("li");
				ulNode.appendChild(liMatchesContainer);
				// Create TABLE to hold matches for current date
				tblMatchesData=document.createElement("table");
				tblMatchesData.className="date-group";
				tblMatchesData.cellPadding="0";
				tblMatchesData.cellSpacing="0";
				liMatchesContainer.appendChild(tblMatchesData);
				tbody=document.createElement("tbody");
				tblMatchesData.appendChild(tbody)
				// For each match in date group extract
				// data and create TABLE TRs
				for(var match in orderedDateGroups[i].matches){
					var liveMatchFlag=false;
					var penalties_str=null;
					for(var matchProperty in orderedDateGroups[i].matches[match]){
						switch(matchProperty){
							case "team_home_name":
								var team_home=orderedDateGroups[i].matches[match][matchProperty];
								if(!team_home || team_home=="undefined")
									team_home="__MSG_unknown__";
							break;
							case "team_visit_name":
								var team_visit=orderedDateGroups[i].matches[match][matchProperty];
								if(!team_visit || team_visit=="undefined")
									team_visit="__MSG_unknown__";
							break;
							case "full_score":
								var score=orderedDateGroups[i].matches[match][matchProperty].split("").join(" ");
							break;
							case "half_score":
								var half_score=orderedDateGroups[i].matches[match][matchProperty].split("").join(" ");
							break;
							case "startdate":
								var startdate=orderedDateGroups[i].matches[match][matchProperty];
							break;
							case "id":
								var id=orderedDateGroups[i].matches[match][matchProperty];
							break;
							case "elapsed_min":
								var elapsed_min=orderedDateGroups[i].matches[match][matchProperty];
							break;
							case "status_id":
								var status=this.getMatchStatus(orderedDateGroups[i].matches[match][matchProperty]);
							break;
							case "penalties_str":
								penalties_str=orderedDateGroups[i].matches[match][matchProperty];
							break;
						}
					}
					// Create HTML row in table
					var trNode=document.createElement("tr");
					trNode.id="match-"+id+"-"+groupedByDate;
					// If no status then see if match is in
					// progress - add elapsed min and live flag
					if(!status){
						if(elapsed_min){
							status=elapsed_min+"'";
							liveMatchFlag=true;
						}
						// If not live then status is ""
						else status="";
					}
					// If live match add 'live' class 
					// and add to live matches array
					if(liveMatchFlag){
						trNode.className="live";
						this.LiveMatchIds.push(id+"-"+groupedByDate);
					}
					// If match is playing or has finished
					// then allow link to match details
					if(status!="" && status!="&nbsp;"){
						this.addClassNameTo(trNode,"selectable");
						_self=this;
						trNode.onclick=function(){
							var matchDetailParams=this.id.split("-");
							_self.showMatchDetail(matchDetailParams[1],matchDetailParams[2]);
						};
					}
					// Create master TD elem
					var tdNode=document.createElement("td");
					// Match status TD
					var tdNodeStatus=tdNode.cloneNode(false);
					tdNodeStatus.className="match-status";
					tdNodeStatus.id="matchstatus-"+id+"-"+groupedByDate;
					tdNodeStatus.innerHTML=(status=="")? "&nbsp;":status;
					trNode.appendChild(tdNodeStatus);
					// Home team TD
					var tdNodeHome=tdNode.cloneNode(false);
					tdNodeHome.className="team-home";
					tdNodeHome.innerHTML=team_home;
					trNode.appendChild(tdNodeHome);
					// Score TD
					var tdNodeScore=tdNode.cloneNode(false);
					tdNodeScore.className="score";
					tdNodeScore.id="score-"+id+"-"+groupedByDate;
					tdNodeScore.innerHTML=score;
					trNode.appendChild(tdNodeScore);
					// Visiting team TD
					var tdNodeVisit=tdNode.cloneNode(false);
					tdNodeVisit.className="team-visit";
					tdNodeVisit.innerHTML=team_visit;
					trNode.appendChild(tdNodeVisit);
					// Add TR to TABLE
					tbody.appendChild(trNode);
					if(penalties_str){
						var trNodePens=document.createElement("tr");
						trNodePens.id="penalties-"+id+"-"+groupedByDate;
						trNodePens.className="score-after-penalties";
						var tdNodePens=document.createElement("td");
						tdNodePens.colSpan="4";
						tdNodePens.innerHTML=penalties_str;
						trNodePens.appendChild(tdNodePens);
						tbody.appendChild(trNodePens);
					}
				}
			}
			matchListingElem.appendChild(ulNode);
			// If there are live matches then
			// init live updates
			if(this.LiveMatchIds.length>0)
				this.initLiveMatchUpdates();                             
		};
		this.initLiveMatchUpdates=function(){
			// Every minute get match data and update
			_self=this;
			setTimeout(function(){
				_self.getLiveMatchData();
				if(_self.LiveMatchIds.length>0) _self.initLiveMatchUpdates();
			},60000);
		};
		this.stopLiveMatchUpdates=function(){
			this.LiveMatchIds=[];
		};
		this.updateLiveMatchesHtml=function(){
			for(var i=0; i<this.LiveMatchIds.length; i++){
				var scoreTD=_gel("score-"+this.LiveMatchIds[i]);
				var minTD=_gel("matchstatus-"+this.LiveMatchIds[i]);
				var matchIdBits=this.LiveMatchIds[i].split("-");
				var matchId=matchIdBits[0];
				var dateGroup=matchIdBits[1];
				// Update score
				scoreTD.innerHTML=this.LiveMatches[dateGroup][matchId].full_score;
				var matchStatus=this.getMatchStatus(this.LiveMatches[dateGroup][matchId].status_id);
				// If status exists and is not HT then stop updating this match
				if(matchStatus && matchStatus!="14"){
					minTD.innerHTML=this.LiveMatches[dateGroup][matchId].matchStatus;
					this.removeClassNameFrom(scoreTD,"live");
					// Remove this match from livematchId array
					this.LiveMatchIds.splice(i,1);
				}
				// If status is HT show status
				else if(matchStatus=="14"){
					minTD.innerHTML=this.LiveMatches[dateGroup][matchId].matchStatus;
				}
				// Else show elapsed min
				//else
					//minTD.innerHTML=this.LiveMatches[dateGroup][matchId].elapsed_min+"'";
				this.addClassNameTo(scoreTD,"updated");
			}
		};
		this.getMatchStatus=function(statusId){
			var status=null;
			switch(statusId){
				case "AET":status="<span title=\"__MSG_match_status_AET__\">__MSG_match_status_AET_short__</span>";break;
				case "1":status="&nbsp;";break;
				case "6":status="<span title=\"__MSG_match_status_GP__\">__MSG_match_status_GP_short__</span>";break;
				case "7":
				case "51":
				case "66":
				case "69":
				case "96":
					status="<span title=\"__MSG_match_status_FT__\">__MSG_match_status_FT_short__</span>";
				break;
				case "14":status="<span title=\"__MSG_match_status_HT__\">__MSG_match_status_HT_short__</span>";break;
				case "61":status="<span title=\"__MSG_match_status_GI__\">__MSG_match_status_GI_short__</span>";break;
				case "70":status="<span title=\"__MSG_match_status_GA__\">__MSG_match_status_GA_short__</span>";break;
				case "121":
				case "177":
					status="<span title=\"__MSG_match_status_GD__\">__MSG_match_status_GD_short__</span>";
				break;	
			}
			return status;
		};
		this.showMatchDetail=function(matchId,dateGroup){
			this.showLoaderFor("ctrMatchDetail");
			// Hide match listing and archive form
			this.toggleDisplay("ctrMatchListing","none");
			this.toggleDisplay("ctrMatchArchive","none");
			// Show match detail container and back button
			_gel("ctrTabMatches").scrollTop=0;
			this.toggleDisplay("ctrMatchDetail","block");
			this.toggleDisplay("ctrMatchDetailBack","block");
			_self=this;
			_gel("clkBackMatchDetailBack").onclick=function(){
				_self.hideMatchDetail();
			};
			// Determine match object and write HTML
			if(!this.Matches[dateGroup] || !this.Matches[dateGroup][matchId]){
				this.onError("05");
				return;
			}
			var matchObj=this.Matches[dateGroup][matchId];
			this.writeMatchDetailHtml(matchObj);
			this.addClassNameTo("ctrTabMatches","fixWidth");
		};
		this.writeMatchDetailHtml=function(thisMatch){
			var timeline=[];
			for(var matchProperty in thisMatch){
				switch(matchProperty){
					case "team_home_name":
						var team_home=thisMatch[matchProperty];
						if(!team_home || team_home=="undefined")
									team_home="__MSG_unknown__";
					break;
					case "team_home":
						var team_home_id=thisMatch[matchProperty];
					break;
					case "team_visit_name":
						var team_visit=thisMatch[matchProperty];
						if(!team_visit || team_visit=="undefined")
									team_visit="__MSG_unknown__";
					break;
					case "team_visit":
						var team_visit_id=thisMatch[matchProperty];
					break;
					case "full_score":var score=thisMatch[matchProperty];break;
					case "venue_name":
						var venue=thisMatch[matchProperty];
					break;
					case "spectator":	var attd=thisMatch[matchProperty];break;
					case "status_id":
						var status=this.getMatchStatus(thisMatch[matchProperty]);
						if(!status) status="";
					break;
					case "startdate":
						var date=this.getListingFormattedDate(this.getDateFromApiFormattedDate(thisMatch[matchProperty]));
					break;
					case "match_goals":
					case "match_cards":
						// Add each goal or booking to timeline
						var goalsOrCards=thisMatch[matchProperty];
						for(var i=0; i<goalsOrCards.length; i++){
							if(goalsOrCards[i].type=="y2") break;
							timeline.push({
								event:(goalsOrCards[i].type=="y" || goalsOrCards[i].type=="r")? "card":"goal",
								minute:goalsOrCards[i].minute,
								team:goalsOrCards[i].team,
								player:goalsOrCards[i].player,
								type:goalsOrCards[i].type
							});
						}
					break;
					case "match_substitutions":
						// Add each substitution to timeline
						var sub=thisMatch[matchProperty];
						for(var i=0; i<sub.length; i++){
							timeline.push({
								event:"substitution",
								minute:sub[i].minute,
								team:sub[i].team,
								player_in:sub[i].player_in,
								player_out:sub[i].player_out
							});
						}
					break;
				}
			}	
			// Sort timeline entries by minute
			timeline.sort(function(a,b){
					var x=parseInt(a.minute);
						var y=parseInt(b.minute);
					return ((x<y)? -1:((x>y)? 1:0));
			});
			// UL for venue/attd LIs
			var ulStats=document.createElement("ul");
			// LI for venue
			var liDate=document.createElement("li");
			liDate.className="match-date";
			liDate.innerHTML=date;
			ulStats.appendChild(liDate);
			// LI for attendance
			var liAttd=document.createElement("li");
			liAttd.className="match-stats";
			if(attd && attd.length>3) attd=attd.replace(/(\d*)(\d\d\d)$/,"$1,$2");
			liAttd.innerHTML=venue+((attd)?" ("+attd+")":"");
			ulStats.appendChild(liAttd);
			// TABLE for match details
			var tblMatchDetail=document.createElement("table");
			tblMatchDetail.cellPadding="0";
			tblMatchDetail.cellSpacing="0";
			tblMatchDetail.className="match-detail";
			tbody=document.createElement("tbody");
			tblMatchDetail.appendChild(tbody);
			// Create TR for teams and score
			var trScoreRow=document.createElement("tr");
			var thMin=document.createElement("th");
			thMin.scope="col";
			thMin.className="minute";
			thMin.innerHTML=status;
			trScoreRow.appendChild(thMin);
			var thHome=thMin.cloneNode(false);
			thHome.className="team-home";
			thHome.innerHTML=team_home;
			trScoreRow.appendChild(thHome);
			var thScore=thMin.cloneNode(false);
			thScore.className="score";
			thScore.innerHTML=score.split("").join(" ");
			trScoreRow.appendChild(thScore);
			var thVisit=thMin.cloneNode(false);
			thVisit.className="team-visit";
			thVisit.innerHTML=team_visit;
			trScoreRow.appendChild(thVisit);
			tbody.appendChild(trScoreRow);
			// Create TRs and TDs for timeline
			for(var i=0; i<timeline.length; i++){
				// Every row has minute
				var trDetailRow=document.createElement("tr");
				var tdMin=document.createElement("td");
				tdMin.className="minute";
				tdMin.innerHTML=timeline[i].minute+"'";
				trDetailRow.appendChild(tdMin);
				// Define home team/icon/visit team entries
				var tdHome=tdMin.cloneNode(false);
				tdHome.className="team-home-player";
				var tdVisit=tdMin.cloneNode(false);
				tdVisit.className="team-visit-player";
				var tdIcon=tdMin.cloneNode(false);
				tdIcon.className="match-event";
				switch(timeline[i].event){
					case "goal":
						var playerStr=timeline[i].player;
						if(typeof(playerStr)=="undefined") playerStr="__MSG_unknown__";
						switch(timeline[i].type){
							case "1":
								// Normal goal
								if(timeline[i].team==team_home_id){
									tdHome.innerHTML="<div title=\""+playerStr+"\">"+playerStr+"</div>";
									tdVisit.innerHTML="&nbsp;";
								}
								else {
									tdHome.innerHTML="&nbsp;";
									tdVisit.innerHTML="<div title=\""+playerStr+"\">"+playerStr+"</div>";
								}
								tdIcon.innerHTML="<span class=\"goal\"><img src=\"http://latest-football-gadget.googlecode.com/files/goal.png\" alt=\"__MSG_event_goal__\" title=\"__MSG_event_goal__\" /></span>";
							break;
							case "2":
							case "8":
							case "13":
							case "18":
								// Penalty
								if(timeline[i].team==team_home_id){
									tdHome.innerHTML="<div title=\""+playerStr+"\">"+playerStr+"</div>";
									tdHome.innerHTML+=" (__MSG_goal_type_pen__)";
									tdVisit.innerHTML="&nbsp;";
									tdIcon.innerHTML="<span class=\"goal\"><img src=\"http://latest-football-gadget.googlecode.com/files/goal.png\" alt=\"__MSG_event_goal__\" title=\"__MSG_event_goal__\" /></span>";
								}
								else {
									tdHome.innerHTML="&nbsp;";
									tdVisit.innerHTML="<div title=\""+playerStr+"\">"+playerStr+"</div>";
									tdVisit.innerHTML+=" (__MSG_goal_type_pen__)";
									tdIcon.innerHTML="<span class=\"goal\"><img src=\"http://latest-football-gadget.googlecode.com/files/goal.png\" alt=\"__MSG_event_goal__\" title=\"__MSG_event_goal__\" /></span>";
								}
							break;
							case "3":
								// Pen missed
								if(timeline[i].team==team_home_id){
									tdHome.innerHTML="<div title=\""+playerStr+"\">"+playerStr+"</div>";
									tdHome.innerHTML+=" (__MSG_goal_type_missedpen__)";
									tdVisit.innerHTML="&nbsp;";
									tdIcon.innerHTML="&nbsp;";
								}
								else {
									tdHome.innerHTML="&nbsp;";
									tdVisit.innerHTML="<div title=\""+playerStr+"\">"+playerStr+"</div>";
									tdVisit.innerHTML+=" (__MSG_goal_type_missedpen__)";
									tdIcon.innerHTML="&nbsp;";
								}
							break;
							case "7":
							case "10":
							case "11":
							case "17":
								// Own goal
								if(timeline[i].team==team_home_id){
									tdHome.innerHTML="<div title=\""+playerStr+"\">"+playerStr+"</div>";
									tdHome.innerHTML+=" (__MSG_goal_type_owngoal__)";
									tdVisit.innerHTML="&nbsp;";
									tdIcon.innerHTML="<span class=\"goal\"><img src=\"http://latest-football-gadget.googlecode.com/files/goal.png\" alt=\"__MSG_event_goal__\" title=\"__MSG_event_goal__\" /></span>";
								}
								else {
									tdHome.innerHTML="&nbsp;";
									tdVisit.innerHTML="<div title=\""+playerStr+"\">"+playerStr+"</div>";
									tdVisit.innerHTML+=" (__MSG_goal_type_owngoal__)";
									tdIcon.innerHTML="<span class=\"goal\"><img src=\"http://latest-football-gadget.googlecode.com/files/goal.png\" alt=\"__MSG_event_goal__\" title=\"__MSG_event_goal__\" /></span>";
								}
							break;
						}				
					break;
					case "card":
						tdIcon.innerHTML=(timeline[i].type=="r")?
							"<span class=\"match_card_red\"><img src=\"http://latest-football-gadget.googlecode.com/files/match_cards_red.png\" alt=\"__MSG_event_red_card__\" title=\"__MSG_event_red_card__\" /></span>":
							"<span class=\"match_card_yellow\"><img src=\"http://latest-football-gadget.googlecode.com/files/match_cards_yellow.png\" alt=\"__MSG_event_yellow_card__\" title=\"__MSG_event_yellow_card__\" /></span>";
						var playerStr=timeline[i].player;
						if(typeof(playerStr)=="undefined") playerStr="__MSG_unknown__";
						var playerHTML="<div title=\""+playerStr+"\">"+playerStr+"</div>";
						if(timeline[i].team==team_home_id){
							tdHome.innerHTML=playerHTML;
							tdVisit.innerHTML="&nbsp;";
						}
						else if(timeline[i].team==team_visit_id){
							tdVisit.innerHTML=playerHTML;
							tdHome.innerHTML="&nbsp;";
						}
					break;
					case "substitution":
						tdIcon.innerHTML="<span class=\"match_substitutions\"><img src=\"http://latest-football-gadget.googlecode.com/files/match_substitution.png\" alt=\"__MSG_event_sub__\" title=\"__MSG_event_sub__\" /></span>";
						var playerInStr=timeline[i].player_in;
						if(typeof(playerInStr)=="undefined") playerInStr="__MSG_unknown__";
						var playerOutStr=timeline[i].player_out;
						if(typeof(playerOutStr)=="undefined") playerOutStr="__MSG_unknown__";
						var playerHTML="<div><span title=\""+playerInStr+" __MSG_event_sub_on__\">"+playerInStr+"</span><br /><span title=\""+playerOutStr+" __MSG_event_sub_off__\">"+playerOutStr+"</span></div>";
						if(timeline[i].team==team_home_id){
							tdHome.innerHTML=playerHTML;
							tdVisit.innerHTML="&nbsp;";
						}
						else if(timeline[i].team==team_visit_id){
							tdVisit.innerHTML=playerHTML;
							tdHome.innerHTML="&nbsp;";
						}
					break;
				}
				// Add TDs to row and then TR to TABLE
				trDetailRow.appendChild(tdHome);
				trDetailRow.appendChild(tdIcon);
				trDetailRow.appendChild(tdVisit);
				tbody.appendChild(trDetailRow);
			}
			var matchDetailElem=_gel("ctrMatchDetail");
			matchDetailElem.innerHTML="";
			matchDetailElem.appendChild(ulStats);
			matchDetailElem.appendChild(tblMatchDetail);
			this.hideLoaderFor("ctrMatchDetail");
		};
		this.hideMatchDetail=function(){
			this.toggleDisplay("ctrMatchDetail","none");
			this.toggleDisplay("ctrMatchDetailBack","none");
			this.toggleDisplay("ctrMatchListing","block");
			this.toggleDisplay("ctrMatchArchive","block");
			_gel("ctrMatchDetail").innerHTML="";
		};
		//////////////////////////////////////
		
		
		//////////////////////////////////////
		//////////////////////////////////////
		// League standing data functions
		//
		this.StandingsData=null;
		this.getLeagueStandingsWhenReady=function(){
			// Check team names are ready as they are displayed
			// Season ID is needed for API call
			if(this.TeamNamesReady && this.selectedSeason)
				this.getLeagueStandings();
			else {
				_self=this;
				setTimeout(function(){_self.getLeagueStandingsWhenReady()},500);
			}
		};
		this.getLeagueStandings=function(){
			var url=this.getApiUrl(
				"standings",
				{
					season_id:this.selectedSeason,
					league_id:this.selectedLeague
				}
			);
			_self=this;
			this.fetchContent("xml",url,function(response){_self.handleStandingsData(response)});
		};
		this.handleStandingsData=function(response){
			this.StandingsData=response;
			// Clear standings array
			this.Standings=[];
			// Get data from nodes
			var standingNodes=this.StandingsData.getElementsByTagName("standing");
			for(var i=0; i<standingNodes.length; i++){
				var standingDataNodes=standingNodes.item(i).childNodes;
				var tmpStandingObj={};
				for(var j=0; j<standingDataNodes.length; j++){
					var standingDataNode=standingDataNodes.item(j);
					tmpStandingObj[standingDataNode.nodeName]=(standingDataNode.firstChild)? standingDataNode.firstChild.nodeValue:"";
				}
				this.Standings[i]=tmpStandingObj;
			}
			// Error handling
			if(this.Standings.length===0){
				this.onError("02");
				return;
			}
			// Order by rank
			this.Standings.sort(function(a,b){
				var x=parseInt(a.rank);
				var y=parseInt(b.rank);
				return ((x<y)? -1:((x>y)? 1:0));
			});
			// Write HTML table and display
			this.writeStandingsHtml();
			this.hideLoaderFor("ctrStandingsTable");
		};
		this.writeStandingsHtml=function(){
			var tblStandings=document.createElement("table");
			tblStandings.cellPadding="0";
			tblStandings.cellSpacing="0";
			tbody=document.createElement("tbody");
			tblStandings.appendChild(tbody);
			// Headers row
			var trHeaders=document.createElement("tr");
			var thRank=document.createElement("th");
			thRank.className="rank";
			thRank.scope="col";
			thRank.innerHTML="&nbsp;";
			trHeaders.appendChild(thRank);
			var thTeam=thRank.cloneNode(false);
			thTeam.className="team-name";
			thTeam.innerHTML="&nbsp;";
			trHeaders.appendChild(thTeam);
			var thP=thRank.cloneNode(false);
			thP.className="played";
			thP.innerHTML="__MSG_games_played_code__";
			trHeaders.appendChild(thP);
			var thW=thRank.cloneNode(false);
			thW.className="wins";
			thW.innerHTML="__MSG_games_won_code__";
			trHeaders.appendChild(thW);
			var thD=thRank.cloneNode(false);
			thD.className="draws";
			thD.innerHTML="__MSG_games_drawn_code__";
			trHeaders.appendChild(thD);
			var thL=thRank.cloneNode(false);
			thL.className="defeits";
			thL.innerHTML="__MSG_games_lost_code__";
			trHeaders.appendChild(thL);
			var thGF=thRank.cloneNode(false);
			thGF.className="goals-for";
			thGF.innerHTML="__MSG_goals_for_code__";
			trHeaders.appendChild(thGF);
			var thGA=thRank.cloneNode(false);
			thGA.className="goals-against";
			thGA.innerHTML="__MSG_goals_against_code__";
			trHeaders.appendChild(thGA);
			var thGD=thRank.cloneNode(false);
			thGD.className="goal-difference";
			thGD.innerHTML="__MSG_goal_difference_code__";
			trHeaders.appendChild(thGD);
			var thPTS=thRank.cloneNode(false);
			thPTS.className="points";
			thPTS.innerHTML="__MSG_points_code__";
			trHeaders.appendChild(thPTS);
			tbody.appendChild(trHeaders);
			// Data rows
			for(var i=0; i<this.Standings.length; i++){
				var trData=document.createElement("tr");
				if(i%2 || i===0)
					trData.className="every-other-row";
				// Rank
				var tdRank=document.createElement("td");
				tdRank.className="rank";
				tdRank.innerHTML=i+1;
				trData.appendChild(tdRank);
				// Team
				var tdTeam=tdRank.cloneNode(false);
				tdTeam.className="team-name";
				var teamStr=this.Teams[this.Standings[i].team_id];
				if(typeof(teamStr)=="undefined") teamStr="__MSG_unknown__";
					// Promoted/relegated/champ/cup flags
					var teamInfoStr="";
					/*
					if(this.Standings[i].champion=="1") teamInfoStr+="<img src=\"http://latest-football-gadget.googlecode.com/files/champion.png\" title=\"__MSG_champion__\" alt=\"__MSG_champion__\" />";
					if(this.Standings[i].cupwinner=="1") teamInfoStr+="<img src=\"http://latest-football-gadget.googlecode.com/files/champion.png\" title=\"__MSG_cupwinner__\" alt=\"__MSG_cupwinner__\" />";
					if(this.Standings[i].promoted=="1") teamInfoStr+="<img src=\"http://latest-football-gadget.googlecode.com/files/promoted.png\" title=\"__MSG_promoted__\" alt=\"__MSG_promoted__\" />";
					if(this.Standings[i].relegated=="1") teamInfoStr+="<img src=\"http://latest-football-gadget.googlecode.com/files/relegated.png\" title=\"__MSG_relegated__\" alt=\"__MSG_relegated__\" />";
					*/
				tdTeam.innerHTML="<div title=\""+teamStr+"\">"+teamStr+"<span>"+teamInfoStr+"</span></div>";
				trData.appendChild(tdTeam);
				// Played
				var tdP=tdRank.cloneNode(false);
				tdP.className="played";
				tdP.innerHTML=this.Standings[i].played;
				trData.appendChild(tdP);
				// Won
				var tdW=tdRank.cloneNode(false);
				tdW.className="wins";
				tdW.innerHTML=this.Standings[i].wins;
				trData.appendChild(tdW);
				// Drawn
				var tdD=tdRank.cloneNode(false);
				tdD.className="draws";
				tdD.innerHTML=this.Standings[i].defeits;
				trData.appendChild(tdD);
				// Lost
				var tdL=tdRank.cloneNode(false);
				tdL.className="defeits";
				tdL.innerHTML=this.Standings[i].draws;
				trData.appendChild(tdL);
				// Goals for
				var tdGF=tdRank.cloneNode(false);
				tdGF.className="goals-for";
				tdGF.innerHTML=this.Standings[i].goals_for;
				trData.appendChild(tdGF);
				// Goals against
				var tdGA=tdRank.cloneNode(false);
				tdGA.className="goals-against";
				tdGA.innerHTML=this.Standings[i].goals_against;
				trData.appendChild(tdGA);
				// Goal difference
				var tdGD=tdRank.cloneNode(false);
				tdGD.className="goal-difference";
				tdGD.innerHTML=this.Standings[i].goals_diff;
				trData.appendChild(tdGD);
				// Points
				var tdPTS=tdRank.cloneNode(false);
				tdPTS.className="points";
				tdPTS.innerHTML=this.Standings[i].points;
				trData.appendChild(tdPTS);
				tbody.appendChild(trData);
			}
			var ctrStandingsTable=_gel("ctrStandingsTable");
			ctrStandingsTable.innerHTML="";
			ctrStandingsTable.appendChild(tblStandings);
		};
		//////////////////////////////////////
		
		
		//////////////////////////////////////
		//////////////////////////////////////
		// Match archive filtering functions
		// - month/year/team select boxes
		this.MatchArchiveMonth=null;
		this.MatchArchiveYear=null;
		this.MatchArchiveTeamId=null;
		this.resetArchiveFilter=function(){
			this.selYearElem=_gel("selYear");
			this.selTeamElem=_gel("selTeam");
			this.selMonthElem=_gel("selMonth");
			_self=this;
			this.selMonthElem.onchange=function(){_self.handleMonthChange()};
			_gel("clkSubmitMatchArchive").onclick=function(){
				_self.hideError();
				_self.handleMatchFilters();
				_self.saveState();
			};
			// Setup select boxes
			this.initMonthSelect();
			this.initYearSelect();
			this.initTeamSelect();
		};
		this.initMatchTab=function(){
			this.writeMatchListingWhenReady();
		};
		this.resetMatchTab=function(){
			this.getMatchData();
			this.writeMatchListingWhenReady();
		};
		this.handleMonthChange=function(){
			if(this.selMonthElem.selectedIndex===0 || this.selMonthElem.selectedIndex==1){
					this.selYearElem.disabled=true;
					this.selYearElem.selectedIndex=0;
					this.selTeamElem.disabled=true;
					this.selTeamElem.selectedIndex=0;
				}
				else {
					this.selYearElem.disabled=false;
					this.selTeamElem.disabled=false;
				}
		};
		this.handleMatchFilters=function(holdTimeoutCheckFromTryAgain){
			this.showLoaderFor("ctrMatchListing","loading");
			// "this week"
			if(this.selMonthElem.selectedIndex===0){
				// Reset filters
				this.searchForSeasonIdCounter=0;
				this.MatchArchiveMonth="";
				this.MatchArchiveYear="";
				this.MatchArchiveTeamId="";
				this.getMatchData(null,null,null,true,false,holdTimeoutCheckFromTryAgain);
				return;
			}
			// "next week"
			else if(this.selMonthElem.selectedIndex==1){
				// Stop automatic season id finding
				this.searchForSeasonIdCounter=3;
				// Calculate date range
				this.CurrentListingTimeBoundary={
					upper:(new Date((new Date()).getTime()+604800000)).getTime()+(new Date()).getTimezoneOffset()*60000,
					lower:(new Date()).getTime()+(new Date()).getTimezoneOffset()*60000
				};
				var fromDate=this.getApiFormattedDate();
				var toDate=this.getApiFormattedDate(new Date((new Date()).getTime()+604800000));
				// Reset filters
				this.MatchArchiveMonth="";
				this.MatchArchiveYear="";
				this.MatchArchiveTeamId="";
				this.getMatchData(fromDate,toDate,null,true,false,holdTimeoutCheckFromTryAgain);
				return;
			}
			// Stop automatic season id finding
			this.searchForSeasonIdCounter=3;
			// Months/year
			var usrFromMonth=this.selMonthElem.options[this.selMonthElem.selectedIndex].value;
			var usrFromYear=this.selYearElem.options[this.selYearElem.selectedIndex].value;
			var usrTeamId=(this.selTeamElem.selectedIndex!=0)? this.selTeamElem.options[this.selTeamElem.selectedIndex].value:null;
			// Save filters
			this.MatchArchiveMonth=usrFromMonth;
			this.MatchArchiveYear=usrFromYear;
			this.MatchArchiveTeamId=usrTeamId;
			this.generateMatchDataRequest(usrFromMonth,usrFromYear,usrTeamId);
		};
		this.generateMatchDataRequest=function(usrFromMonth,usrFromYear,usrTeamId){
			// Format date params
			var usrFromDate="01 "+usrFromMonth+" "+usrFromYear;
			switch(this.arrayIndexOf(this.monthNames.oleoleCodes,usrFromMonth)){
				case "1":
					// Feb
					if(this.isLeapYear(usrFromYear)) var days=29;
					else var days=28;
				break;
				case "8":
				case "3":
				case "5":
				case "10":
					// Sep, Apr, Jun, Nov
					var days=30;
				break;
				default:
					var days=31;
			}
			var usrToDate=days+" "+usrFromMonth+" "+usrFromYear;
			// Generate timezone adjusted dates
			this.CurrentListingTimeBoundary={
					upper:this.getDateFromApiFormattedDate(usrToDate,false,true).getTime()+86400000+this.getDateFromApiFormattedDate(usrToDate,false,true).getTimezoneOffset()*60000,
					lower:this.getDateFromApiFormattedDate(usrFromDate,false,true).getTime()+this.getDateFromApiFormattedDate(usrFromDate,false,true).getTimezoneOffset()*60000
				};
			if(this.getDateFromApiFormattedDate(usrFromDate).getTimezoneOffset().toString().substr(0,1)!="-"){
				usrToDate=this.getApiFormattedDate(this.getDateFromApiFormattedDate(usrToDate,true));
				usrFromDate=usrFromDate.replace(/ /g,"%20");
			}
			else {
				usrToDate=usrToDate.replace(/ /g,"%20");
				usrFromDate=this.getApiFormattedDate(this.getDateFromApiFormattedDate(usrFromDate,true));
			}
			// If team names are ready then get data and write listing
			if(this.TeamNamesReady)
				this.getMatchData(usrFromDate,usrToDate,usrTeamId,true,false,true);
			else {
				// If not then get data and render when ready
				this.MatchListingReady=false;
				this.getMatchData(usrFromDate,usrToDate,usrTeamId,false,false,false);
				this.writeMatchListingWhenReady();
			}
		};
		this.isLeapYear=function(datea){
			datea=parseInt(datea);
			if(datea%4==0){
				if(datea%100!=0){
					return true;
				}
				else {
					if(datea%400==0)
						return true;
					else
						return false;
				}
			}
			return false;
		};
		this.initYearSelect=function(){
			this.selYearElem.options.length=0;
			var currYear=(new Date()).getFullYear();
			var counter=0,selIdx=null;
			while(currYear>2006){
				this.selYearElem.options[this.selYearElem.options.length]=new Option(currYear,currYear);
				currYear=parseInt(currYear)-1;
			}
			if(selIdx || selIdx===0){
				this.selYearElem.selectedIndex=selIdx;
				this.selYearElem.disabled=false;
			}
			else
				this.selYearElem.disabled=true;
		};
		this.initMonthSelect=function(){
			this.selMonthElem.options.length=0;
			var selIdx=0;
			this.selMonthElem.options[0]=new Option("__MSG_matchlisting_view_thisweek__","this_week");
			this.selMonthElem.options[1]=new Option("__MSG_matchlisting_view_nextweek__","next_week");
			this.addClassNameTo(this.selMonthElem.options[1],"break-after");
			for(var i=2; i<=this.monthNames.short.length+1; i++){
				this.selMonthElem.options[this.selMonthElem.options.length]=new Option(this.monthNames.short[i-2],this.monthNames.oleoleCodes[i-2]);
			}
			this.selMonthElem.selectedIndex=selIdx;
		};
		//////////////////////////////////////
		
		window.alert=function(msg) {
			if(!confirm(msg)) throw new Error("Force Quit");
		};
		
		
		//////////////////////////////////////
		//////////////////////////////////////
		// Country select functions
		// - setCountries
		// - initCountrySelect (DOM)
		//
		this.Countries=[];
		this.setCountries=function(countriesToAdd){
			countriesToAdd.sort(function(a,b){
				var x=a.Name;
				var y=b.Name;
				return ((x<y)? -1:((x>y)? 1:0));
			});
			for(var i=0; i<countriesToAdd.length; i++){
				var tmpCountryObj={};
				var countryId=countriesToAdd[i].ID.split("-");
				tmpCountryObj.name=countriesToAdd[i].Name;
				tmpCountryObj.id=countryId[0];
				tmpCountryObj.defaultLeague=countriesToAdd[i].DefaultLeague;
				if(countryId[1])
					tmpCountryObj.label=countryId[1];
				this.Countries[i]=tmpCountryObj;
			}
		};
		this.initCountrySelect=function(){
			this.selCountryElem=_gel("selCountry");
			for(var i=0; i<this.Countries.length; i++){
				this.selCountryElem.options[i]=new Option(this.Countries[i].name.replace("&#39;","'"),this.Countries[i].id);
				if(this.Countries[i].id==this.selectedCountry.split("-")[0]){
					if(this.selectedCountryLabel){
						if(this.selectedCountryLabel==this.Countries[i].name) var selIdx=i;
					}
					else var selIdx=i;
				}
			}
			this.selCountryElem.selectedIndex=selIdx;
			this.getLeagueNamesForCountry();
			// When a different country is selected
			_self=this;
			this.selCountryElem.onchange=function(){
				_self.selLeagueElem.disabled=true;
				_self.selLeagueElem.options.length=1;
				_self.selLeagueElem.options[0]=new Option("...");
				_self.selectedLeague=null;
				// Save selected country and get
				// new league names
				_self.selectedCountry=this.options[this.selectedIndex].value;
				if(_self.selectedCountry.toLowerCase()=="gb"){
					_self.selectedCountryLabel=this.options[this.selectedIndex].text;
				}
				else {
					_self.selectedCountryLabel=null;
				}
				_self.getLeagueNamesForCountry();
				// If league select has been filled
				// then call onLeagueChange())
				_self.checkForSelectedLeague();
			};
		};
		this.checkForSelectedLeague=function(){
			if(this.selectedLeague)
				this.onLeagueChange()
			else {
				_self=this;
				setTimeout(function(){_self.checkForSelectedLeague()},500);
			}
		};
		//////////////////////////////////////
		
		
		//////////////////////////////////////
		//////////////////////////////////////
		// League select functions
		// - getVenueNames
		//
		this.VenueData=null;
		this.getVenueNames=function(){
			var url=this.getApiUrl("venues");
			_self=this;
			this.fetchContent("xml",url,function(response){_self.handleVenueData(response)});
		};
		this.handleVenueData=function(response){
			this.VenueData=response;
			this.Venues=[];
			var venueNodes=this.VenueData.getElementsByTagName("venue");
			for(var i=0; i<venueNodes.length; i++){
				var tmpVenueObj={};
				var venueDataNodes=venueNodes.item(i).childNodes;
				for(var j=0; j<venueDataNodes.length; j++){
					var nodeName=venueDataNodes.item(j).nodeName;
					if(nodeName=="name" || nodeName=="id"){
						tmpVenueObj[nodeName]=venueDataNodes.item(j).firstChild.nodeValue;
					}
				}
				this.Venues[tmpVenueObj.id]=tmpVenueObj.name;
			}
		};
		//////////////////////////////////////
		
		
		//////////////////////////////////////
		//////////////////////////////////////
		// League data functions and select
		// elem handler
		// - getLeagueNamesForCountry (DOM)
		// - getTeamAndPlayerNames
		// - initTeamSelect (DOM)
		//
		this.LeagueData=null;
		this.TeamPlayerData=null;
		this.TeamNamesReady=false;
		this.CustomLeagueNames=[];
		this.setCustomLeagueNames=function(userObj){
			for(var leagueMap in userObj){
				this.CustomLeagueNames.push(userObj[leagueMap]);
			}
			var localeLeagueNames=this.Prefs.getMsg("custom_league_names");
			if(localeLeagueNames){
				localeLeagueArr=localeLeagueNames.split(",");
				for(var localeLeagueEntry in localeLeagueArr){
					var localeLeagueEntryBits=localeLeagueArr[localeLeagueEntry].split("=");
					this.CustomLeagueNames.push({
						OriginalName:localeLeagueEntryBits[0].replace(/^\s?(\w+(\s\w+)*)\s?$/,"$1"),
						NewName:localeLeagueEntryBits[1].replace(/^\s?(\w+(\s\w+)*)\s?$/,"$1")
					});
				}
			}
			this.CustomLeagueNames.reverse();
		};
		this.getLeagueNamesForCountry=function(){
			// Return league names/ids for
			// a given country
			var url=this.getApiUrl(
				"leagues",
				{
					country:this.selectedCountry,
					gender:this.selectedSex,
					showteams:0
				}
			);
			_self=this;
			this.fetchContent("xml",url,function(response){_self.handleLeaguesData(response,"league_names")});
		};
		this.getTeamNamesForLeague=function(){
			// Ensure flag is false
			this.TeamNamesReady=false;
			// Return team/player names/ids for
			// a given league
			var url=this.getApiUrl(
				"leagues",
				{
					country:this.selectedCountry,
					gender:this.selectedSex,
					id:this.selectedLeague,
					showteams:1
				}
			);
			_self=this;
			this.fetchContent("xml",url,function(response){_self.handleLeaguesData(response,"team_names")});
		};
		this.handleLeaguesData=function(response,mode){
			switch(mode){
				case "league_names":
					this.extractLeagueNames(response);
				break;
				case "team_names":
					this.TeamNamesReady=false;
					this.extractTeamNames(response);
				break;
			}
		};
		this.extractLeagueNames=function(response){
			this.LeagueData=response;
			this.Leagues=[];
			if(this.selectedCountry.toLowerCase()=="gb"){
				var nameToMap=this.selCountryElem.options[this.selCountryElem.selectedIndex].text;
				for(var i=0; i<this.Countries.length; i++){
					if(this.Countries[i].id.toLowerCase()=="gb" &&
						this.Countries[i].name==nameToMap && "__MSG_default_country_code__"=="GB-England")
						var countryLbl=this.Countries[i].label;
				}
			}
			var leagueNodes=this.LeagueData.getElementsByTagName("league");
			for(var i=0; i<leagueNodes.length; i++){
				var tempProperties={};
				var leagueDataNodes=leagueNodes.item(i).childNodes;
				if(!leagueDataNodes) break;
				for(var j=0; j<leagueDataNodes.length; j++){
					if(leagueDataNodes.item(j).nodeName=="name" ||
						 leagueDataNodes.item(j).nodeName=="id" ||
						 leagueDataNodes.item(j).nodeName=="country"){
						tempProperties[leagueDataNodes.item(j).nodeName]=leagueDataNodes.item(j).firstChild.nodeValue;
					}
				}
				// Overwrite name with custom (if required)
				var idx=this.arrayIndexOf(this.CustomLeagueNames,tempProperties.name,"OriginalName");
				if(idx>-1)
					tempProperties.name=this.CustomLeagueNames[idx].NewName;
				// Add to leagues array
				if(countryLbl){
					this.Leagues.push({
						name:tempProperties.name,
						id:tempProperties.id,
						country:tempProperties.country
					});
				}
				else {
					this.Leagues.push({
						name:tempProperties.name,
						id:tempProperties.id
					});
				}
			}
			// Sort leagues alphabetically
			if(countryLbl){
				var tempLeaguesGroupings=[];
				for(var i=0; i<this.Leagues.length; i++){
					if(!tempLeaguesGroupings[this.Leagues[i].country])
						tempLeaguesGroupings[this.Leagues[i].country]=[];
					tempLeaguesGroupings[this.Leagues[i].country].push({name:this.Leagues[i].name,id:this.Leagues[i].id});
				}
				this.Leagues=[];
				for(var countryGrouping in tempLeaguesGroupings){
					tempLeaguesGroupings[countryGrouping].sort(function(a,b){
						var x=a.name;
						var y=b.name;
						return ((x<y)? -1:((x>y)? 1:0));
					});
					if(countryGrouping==countryLbl){
						for(var i=0; i<tempLeaguesGroupings[countryGrouping].length; i++){
							this.Leagues.push(tempLeaguesGroupings[countryGrouping][i]);
						}
					}
				}
			}
			else {
				this.Leagues.sort(function(a,b){
					var x=a.name;
					var y=b.name;
					return ((x<y)? -1:((x>y)? 1:0));
				});
			}
			// When ready write league select
			this.writeLeagueSelect();
		};
		this.onLeagueChange=function(){
			// Save selected league
			this.selectedLeague=this.selLeagueElem.options[this.selLeagueElem.selectedIndex].value;
			// Get team/player names and reset filters
			this.onLeagueSelected();
			// Clear current season
			this.CurrentSeason=null;
			// Empty tab contents
			this.insertHTML("ctrMatchListing","");
			this.insertHTML("ctrStandingsTable","");
			this.insertHTML("ctrNews","");
			// Reload matches tab
			this.switchTab("ctrTabMatches");
		};
		this.writeLeagueSelect=function(){
			this.selLeagueElem=_gel("selLeague");
			this.selLeagueElem.disabled=false;
			this.selLeagueElem.options.length=0;
			// Get default league for selected country
			var defaultLeague="";
			for(var i=0; i<this.Countries.length; i++) {
				if(this.Countries[i].id==this.selectedCountry){
					if(this.selectedCountryLabel){
						if(this.selectedCountryLabel==this.Countries[i].name) defaultLeague=this.Countries[i].defaultLeague;
					}
					else
						defaultLeague=this.Countries[i].defaultLeague;
				}
			}
			var selIdx=0;
			for(var i=0; i<this.Leagues.length; i++) {
				this.selLeagueElem.options[i]=new Option(this.Leagues[i].name,this.Leagues[i].id);
				if(this.Leagues[i].id==this.selectedLeague)
					selIdx=i;
				else if(this.Leagues[i].id==defaultLeague && selIdx===0)
					selIdx=i;
			}
			this.selLeagueElem.selectedIndex=selIdx;
			// When a different league is selected
			_self=this;
			this.selLeagueElem.onchange=function(){_self.onLeagueChange()};
			// Set selected league and save
			var selectOption=this.selLeagueElem.options[selIdx];
			if(!selectOption){
				this.onError("06");
				this.selLeagueElem.options[0]=new Option("__MSG_error_09__");
				this.selLeagueElem.disabled=true;
				return;
			}
			this.selLeagueElem.disabled=false;
			this.selectedLeague=selectOption.value;
		};
		this.extractTeamNames=function(response){
			// Reset all objects
			this.TeamPlayerData=response;
			this.Teams={};
			this.Players={};
			// Team names
			var teamNodes=response.getElementsByTagName("team");
			for(var i=0; i<teamNodes.length; i++){
				var tmpTeamObj={};
				var teamDataNodes=teamNodes.item(i).childNodes;
				for(var j=0; j<teamDataNodes.length; j++){
					var nodeName=teamDataNodes.item(j).nodeName;
					if(nodeName=="id" || nodeName=="name"){
						tmpTeamObj[nodeName]=teamDataNodes.item(j).firstChild.nodeValue;
					}
				}
				this.Teams[tmpTeamObj.id]=tmpTeamObj.name;
			}
			this.TeamNamesReady=true;
			this.writeTeamSelect();
		};
		this.initTeamSelect=function(){
			this.selTeamElem=_gel("selTeam");
			this.selTeamElem.disabled=true;
			if(!this.TeamNamesReady){
				this.selTeamElem.options.length=0;
				this.selTeamElem.options[0]=new Option("...");
			}
		};
		this.writeTeamSelect=function(){
			// Sort team names alphabetically
			var teamsToWrite=[];
			for(var teamId in this.Teams){
				//if(this.TeamIdsInSelectedLeague.indexOf(teamId)==-1) continue;
				teamsToWrite.push({name:this.Teams[teamId],id:teamId});
			}
			teamsToWrite.sort(function(a,b){
				var x=a.name;
				var y=b.name;
				return ((x<y)? -1:((x>y)? 1:0));
			});
			// Write select box
			if(!this.selTeamElem)
				this.selTeamElem=_gel("selTeam");
			this.selTeamElem.options.length=0;
			this.selTeamElem.options[0]=new Option("__MSG_all_teams_option__");
			var selIdx=null;
			for(var i=1; i<=teamsToWrite.length; i++){
				this.selTeamElem.options[i]=new Option(teamsToWrite[i-1].name, teamsToWrite[i-1].id);
			}
			if(selIdx || selIdx===0){
				this.selTeamElem.selectedIndex=selIdx;
				this.selTeamElem.disabled=false;
			}
		};
		//////////////////////////////////////
		
		
		//////////////////////////////////////
		//////////////////////////////////////
		// Date formatting functions
		this.monthNames={
			short:[
				"__MSG_month_00_short__",
				"__MSG_month_01_short__",
				"__MSG_month_02_short__",
				"__MSG_month_03_short__",
				"__MSG_month_04_short__",
				"__MSG_month_05_short__",
				"__MSG_month_06_short__",
				"__MSG_month_07_short__",
				"__MSG_month_08_short__",
				"__MSG_month_09_short__",
				"__MSG_month_10_short__",
				"__MSG_month_11_short__"
			],
			long:[
				"__MSG_month_00_long__",
				"__MSG_month_01_long__",
				"__MSG_month_02_long__",
				"__MSG_month_03_long__",
				"__MSG_month_04_long__",
				"__MSG_month_05_long__",
				"__MSG_month_06_long__",
				"__MSG_month_07_long__",
				"__MSG_month_08_long__",
				"__MSG_month_09_long__",
				"__MSG_month_10_long__",
				"__MSG_month_11_long__"
			],
			oleoleCodes:[
				"Jan",
				"Feb",
				"Mar",
				"Apr",
				"May",
				"Jun",
				"Jul",
				"Aug",
				"Sep",
				"Oct",
				"Nov",
				"Dec"
			]};
		this.dayNames=[
			"__MSG_day_00__",
			"__MSG_day_01__",
			"__MSG_day_02__",
			"__MSG_day_03__",
			"__MSG_day_04__",
			"__MSG_day_05__",
			"__MSG_day_06__"
		];
		this.arrayIndexOf=function(arr,v,objectName){
			for(var i in arr){
				if(objectName){
					if(arr[i][objectName]===v) return i;
				}
				else {
					if(arr[i]===v) return i;
				}
			}
			return -1;
		};
		this.getDateFromApiFormattedDate=function(date,doNotReturnTime,doNotTimezoneAdjust){
			var dateBits=date.split(" ");
			var date=dateBits[0];
			var month=this.arrayIndexOf(this.monthNames.oleoleCodes,dateBits[1]);
			var year=dateBits[2];
			if(dateBits[3]){
				var hhmmss=dateBits[3].split(":");
				var returnDate=new Date(year,month,date,hhmmss[0],hhmmss[1],hhmmss[2]);
			}
			else
				var returnDate=new Date(year,month,date);
			if(!doNotTimezoneAdjust){
				// Convert from GMT to client timezone -
				// Date.getTimeZoneOffset returns mins so *60000 to get ms
				var timeWithOffset=returnDate.getTime()-returnDate.getTimezoneOffset()*60000;
				returnDate.setTime(timeWithOffset);
			}
			// If time was not included then reset to 00:00
			if(!dateBits[3] || doNotReturnTime)
				returnDate.setHours(0,0,0,0);
			return returnDate;
		};
		this.getApiFormattedDate=function(dateObj){
			if(!dateObj) var dateObj=new Date();
			// Convert to GMT
			var timeWithOffset=dateObj.getTime()+dateObj.getTimezoneOffset()*60000;
			dateObj.setTime(timeWithOffset);
			return dateObj.getDate()+"%20"+this.monthNames.oleoleCodes[dateObj.getMonth()]+"%20"+dateObj.getFullYear();
		};
		this.TodaysFormattedDate=this.getApiFormattedDate();
		this.getListingFormattedDate=function(dateObj){
			// NOTE: Passed date param should be timezone corrected
			// If language is en then include "st","nd","rd" or "th"
			if(_args()["lang"]=="en"){
				var date=dateObj.getDate().toString();
				var dateSubscrId=date.substr(date.length-1);
				if(date.length==2){
					if(date.substr(date.length-2,1)=="1") dateSubscrId="4";
				}
				switch(dateSubscrId){
					case "1":var dateSubscr="st";break;
					case "2":var dateSubscr="nd";break;
					case "3":var dateSubscr="rd";break;
					default:var dateSubscr="th";
				}
				var formattedString=this.dayNames[dateObj.getDay()]+" "+date+"<sup>"+dateSubscr+"</sup> "+this.monthNames.long[dateObj.getMonth()];
			}
			else
				var formattedString=this.dayNames[dateObj.getDay()]+" "+date+" "+this.monthNames.long[dateObj.getMonth()];
			if(dateObj.getMonth()===0 && dateObj.getFullYear()>2008)
				formattedString+=" "+dateObj.getFullYear();
			// Kick-off time
			if(dateObj.getTime()>(new Date()).getTime()){
				var kickOffHrs=dateObj.getHours();
				var kickOffMins=dateObj.getMinutes();
				if(kickOffMins===0) kickOffMins="00";
				formattedString+=" ("+kickOffHrs+":"+kickOffMins+")";
			}
			return formattedString;
		};
		//////////////////////////////////////
		
		
		//////////////////////////////////////
		//////////////////////////////////////
		// Generate API URL function
		//
		this.getApiUrl=function(methodName,params){
			if(typeof(params)=="object") {
				var paramsStr="";
				for(var param in params){
					paramsStr+="&"+param+"="+params[param];
				}
			}
			else if(params) var paramsStr=params;
			else var paramsStr="";
			return "http://www.oleole.com/api/"+methodName+"?api_key=VYDmo0KTSz5OQilTtCiezQ=="+paramsStr;
		};
		//////////////////////////////////////
		
		
		//////////////////////////////////////
		//////////////////////////////////////
		// News search functions
		// 
		this.NewsSearchQuery=null;
		this.resetNewsFilter=function(andGetResults){
			// Check for leagues array
			if(!this.Leagues){
				_self=this;
				setTimeout(function(){_self.resetNewsFilter()},500);
				return;
			}
			// Generate search query string
			var leagueStr="";
			for(var i=0; i<this.Leagues.length; i++){
				if(this.Leagues[i].id==this.selectedLeague){
					leagueStr=this.Leagues[i].name;
					break;
				}
			}
			if(leagueStr!="") this.NewsSearchQuery="(\""+leagueStr+"\" AND \"__MSG_football_term__\")";
			else this.NewsSearchQuery="__MSG_football_term__";
			// Add to input txt box
			this.txtNewsSearch=_gel("txtNewsSearch");
			this.txtNewsSearch.value=this.NewsSearchQuery;
			if(andGetResults)
				this.getNewsResults();
			// Onclick handler
			_self=this;
			_gel("clkSubmitNewsSearch").onclick=function(){
				_self.hideError();
				_self.NewsSearchQuery=_gel("txtNewsSearch").value;
				_self.getNewsResults();
				_self.saveState();
			};
			// Enter key press handler
			document.frmNewsSearch.onkeypress=function(e){
				var characterCode;
				if(e && e.which){
					e=e
					characterCode=e.which
				}
				else if(event) {
					e=event
					characterCode = e.keyCode 
				}
				if(characterCode==13){
					_self.hideError();
					_self.NewsSearchQuery=_gel("txtNewsSearch").value;
					_self.getNewsResults();
					_self.saveState();
					return false;
				}
				return true;
			};
		};
		this.getNewsResults=function(){
			//this.newsSearchLocation=(this.selectedCountry.toLowerCase()=="gb")? "uk":_gel("selCountry").options[_gel("selCountry").selectedIndex].text;
			this.newsSearchLocation=_gel("selCountry").options[_gel("selCountry").selectedIndex].text;
			var newsSearchUrl="http://news.google.com/news?hl="+(_args()["lang"]||"en")+"&svnum=10&as_drrb=q&as_qdr=&as_mind=29&as_minm=7&as_maxd=28&as_maxm=8&q="+_esc(this.NewsSearchQuery)+"&ie=UTF-8&scoring=n&output=atom";
			_self=this;
			this.fetchContent("json",newsSearchUrl,function(response){_self.handleNewsResults(response)});
		};
		this.handleNewsResults=function(feed){
			var newsEntries=feed.Entry;
			var htmlToWrite="";		
			if(!newsEntries){
				this.onError("00");
				return;
			}	
			for(var i=0; i<newsEntries.length; i++){
				var thisEntry=feed.Entry[i];
				var summary=thisEntry.Summary;
				summary=summary.replace(/<table (.*?)>/g,"<table>");
				summary=summary.replace(/<td (.*?)>/g,"<td>");
				summary=summary.replace(/<br><div>/g,"<div>");
				summary=summary.replace(/ style=".*?"/g,"");
				//Ensure all the returned links open in a new window and not within the gadget
				summary=summary.replace(/(<a) .*?(target=".*?")?/g,"$1 target=\"_blank\" ");
				htmlToWrite+=summary;
			}
			var gAlertStr="__MSG_google_alerts__";
			gAlertStr=gAlertStr.replace(/\[(.+)\]/,"<a href=\"http://www.google.com/alerts?q="+_esc(this.NewsSearchQuery)+"\" target=\"_blank\" title=\"$1\">$1</a>");
			htmlToWrite+="<div id=\"ctrGoogleAlerts\">"+gAlertStr+"</div>";
			this.insertHTML("ctrNews",htmlToWrite);
			this.hideLoaderFor("ctrNews");
		};
		//////////////////////////////////////
		
		
		//////////////////////////////////////
		//////////////////////////////////////
		// Season names
		// - getSeasonNames (DOM)
		//
		this.SeasonsData=null;
		this.Seasons=[];
		this.selectedSeason=null;
		this.CurrentSeason=null;
		this.selSeasonElem=null;
		this.initSeasonsFilter=function(){
			this.selSeasonElem=_gel("selSeasons");
			this.selSeasonElem.disabled=true;
			this.selSeasonElem.options[0]=new Option("Loading...");
		};
		this.resetSeasonsFilter=function(){
			this.initSeasonsFilter();
			this.getSeasonNames();
		};
		this.getSeasonNames=function(){
			var url=this.getApiUrl(
				"seasons",
				{
					league_id:this.selectedLeague
				}
			);
			_self=this;
			this.fetchContent("xml",url,function(response){_self.handleSeasonsData(response)});
		};
		this.handleSeasonsData=function(response){
			this.SeasonsData=response;
			this.Seasons=[];
			var seasonNodes=this.SeasonsData.getElementsByTagName("season");
			for(var i=0; i<seasonNodes.length; i++){
				var tmpSeasonObj={};
				var seasonDataNodes=seasonNodes.item(i).childNodes;
				for(var j=0; j<seasonDataNodes.length; j++){
					var nodeName=seasonDataNodes.item(j).nodeName;
					if(nodeName=="name" || nodeName=="id"){
						tmpSeasonObj[seasonDataNodes.item(j).nodeName]=seasonDataNodes.item(j).firstChild.nodeValue;
					}
				}
				this.Seasons.push({name:tmpSeasonObj.name,id:tmpSeasonObj.id});
			}
			// Sort alphabetically (inherently chronological)
			this.Seasons.sort(function(a,b){
				var x=b.name;
				var y=a.name;
				return ((x<y)? -1:((x>y)? 1:0));
			});
			// Write html
			this.writeSeasonsSelect();
		};
		this.writeSeasonsSelect=function(){
			if(!this.CurrentSeason){
				setTimeout(function(){_self.writeSeasonsSelect()},500);
				return;
			}
			this.selectedSeason=this.CurrentSeason;
			this.selSeasonElem.disabled=false;
			this.selSeasonElem.options.length=0;
			var selIdx=0;
			for(var i=0; i<this.Seasons.length; i++) {
				this.selSeasonElem.options[i]=new Option(this.Seasons[i].name,this.Seasons[i].id);
				if(this.Seasons[i].id==this.selectedSeason)
					selIdx=i;
			}
			this.selSeasonElem.selectedIndex=selIdx;
			// Configure submit button
			_self=this;
			_gel("clkSubmitStandingsArchive").onclick=function(){
				_self.hideError();
				var selSeasonElem=_gel("selSeasons");
				_self.selectedSeason=selSeasonElem.options[selSeasonElem.selectedIndex].value;
				_self.getLeagueStandings();
				_self.saveState();
			}
		};
		//////////////////////////////////////
		
	}
	
	// Gadget class
	function Gadget() {
		
		//////////////////////////////////////
		// Loader styles
		this.showLoaderFor=function(elem){
			// Hide any errors
			this.hideError();
			this.addClassNameTo(elem,"loading");
		};
		this.hideLoaderFor=function(elem){
			this.removeClassNameFrom(elem,"loading");
		};
		
		//////////////////////////////////////
		// Error methods
		this.onError=function(){};
		this.showError=function(){
			this.addClassNameTo("ctrGadget","error");
		};
		this.hideError=function(){
			this.removeClassNameFrom("ctrGadget","error");
		};
		
		//////////////////////////////////////
		// HTML render methods
		this.insertHTML=function(elem,htmlStr,pos) {
			if(typeof(elem)=="string") elem=_gel(elem);
			if(!pos)
				elem.innerHTML=htmlStr;
			else if(pos=="top")
				elem.innerHTML=htmlStr+elem.innerHTML;
			else if(pos=="bottom")
				elem.innerHTML=elem.innerHTML+htmlStr;
		};
		this.insertHTMLAtTopOf=function(elem,htmlStr) {
			this.insertHTML(elem,htmlStr,"top");
		};
		this.insertHTMLAtBottomOf=function(elem,htmlStr) {
			this.insertHTML(elem,htmlStr,"bottom");
		};
		
		//////////////////////////////////////
		// User preferences
		this.Prefs=new _IG_Prefs();
		this.getPref=function(dataType,prefName) {
			switch(dataType) {
				case "string":
					var prefValue=this.Prefs.getString(prefName);
				break;
				case "int":
					var prefValue=this.Prefs.getInt(prefName);
				break;
				case "bool":
					var prefValue=this.Prefs.getBool(prefName);
				break;
				case "array":
					var prefValue=this.Prefs.getArray(prefName);
				break;
				case "msg":
					var prefValue=this.Prefs.getMsg(prefName);
				break;
				default:
					var prefValue=null;
			}
			return prefValue;
		};
		this.setPref=function(prefName,prefValue) {
			if(typeof(prefValue)=="object")
				this.Prefs.setArray(prefName,prefValue);
			else
				this.Prefs.set(prefName,prefValue);
		};
		
		//////////////////////////////////////
		// Set container title
		this.setContainerTitle=function(titleStr) {
			if(_IG_SetTitle)
				_IG_SetTitle(titleStr);
		};
		
		//////////////////////////////////////
		// Init Gadget object
		// - fire Gadget.onLoaded when loaded
		this.init=function() {
			_self=this;
			_IG_RegisterOnloadHandler(function(){_self.onLoaded()});
		};
		this.onLoaded=function(){};
		
		//////////////////////////////////////
		// Fetch remote content
		this.fetchCounter=1;
		this.fetchCallBackActivated
		this.fetchContent=function(contentType,url,callback,checkTimeout,refreshCacheSeconds){
			if(!checkTimeout){
				_self.fetchContentNow(contentType,url,callback,refreshCacheSeconds);
				return;
			}
			// Prepare fetch
			this.fetchContentNow(contentType,url,callback,refreshCacheSeconds,true);
			// Start timeout check
			_self=this;
			setTimeout(function(){
				if(!_self.fetchCallBackActivated && _self.fetchCounter<3){
					//console.log("fetching again")
					_self.fetchCounter++;
					_self.fetchContent(contentType,url,callback,true,refreshCacheSeconds);
				}
				else {
					if(_self.fetchCounter==3)
						_self.onError("06");
					_self.fetchCallBackActivated=false;
					_self.fetchCounter=1;
				}
			},5500);
		};
		this.fetchContentNow=function(contentType,url,callback,refreshCacheSeconds,checkTimeout){
			_self=this;
			switch(contentType){
				case "text":
					_IG_FetchContent(url,function(response){_self.fetchCallBackActivated=true;callback(response)});
				break;
				case "xml":
					if(checkTimeout){
						if(refreshCacheSeconds){
							_IG_FetchXmlContent(url,function(response){_self.fetchCallBackActivated=true;callback(response)},{refreshInterval:refreshCacheSeconds});
						}
						else
							_IG_FetchXmlContent(url,function(response){_self.fetchCallBackActivated=true;_self.fetchXmlCallback(response,callback)});
					}
					else {
						if(refreshCacheSeconds)
							_IG_FetchXmlContent(url,function(response){callback(response)},{refreshInterval:refreshCacheSeconds});
						else
							_IG_FetchXmlContent(url,function(response){_self.fetchXmlCallback(response,callback)});
					}
				break;
				case "json":
					_IG_FetchFeedAsJSON(url,function(response){_self.fetchCallBackActivated=true;callback(response)},10,true);
				break;
			}
		};
		this.fetchJsonCallBack=function(repsonse,callback){
			if(!feed.Entry || feed==null)
				this.onError("00");
			else
				callback(response);
		};
		this.fetchXmlCallback=function(response,callback){
			// Validate XML response
			if(response==null || typeof(response)!="object" || response.firstChild==null)
				this.onError("06");
			else
				callback(response);
		};
		
		//////////////////////////////////////
		// Resize functions
		this.resizeTo=function(height,onResized) {
			if(height)
				_gel("gadget-frame").style.height=height+"px";
			window.setTimeout("_IG_AdjustIFrameHeight()",10);
			if(onResized)
				window.setTimeout(onResized,700);
		};
		this.fitToContent=function(onResized) {
			this.resizeTo(null,onResized);
		};
		
		//////////////////////////////////////
		// Toggle display/visibility styles
		this.toggleDisplay=function(elem,displayStyle) {
			if(typeof(elem)=="string") elem=_gel(elem);
			elem.style.display=displayStyle;
		};
		this.toggleVisibility=function(elem,visibilityStyle) {
			if(typeof(elem)=="string") elem=_gel(elem);
			elem.style.visibility=visibilityStyle;
		};
		
		//////////////////////////////////////
		// Add/remove specified classname to element
		this.addClassNameTo=function(elem,className) {
			if(typeof(elem)=="string") elem=_gel(elem);
			var currClassName=elem.className;
			var patternToCheck=new RegExp("\w?"+className);
			if(!currClassName.match(patternToCheck))
				elem.className=(currClassName.length>=1)? currClassName+" "+className:className;
		};
		this.removeClassNameFrom=function(elem,className) {
			if(typeof(elem)=="string") elem=_gel(elem);
			if(typeof(className)!="object") className=[className];
			var currClassName=elem.className;
			for(var i=0; i<className.length; i++) {
				var patternToRemove=new RegExp("\w?"+className[i],"g");
				elem.className=currClassName.replace(patternToRemove,"");
			}
		};
		
		//////////////////////////////////////
		// Init gadget
		this.init();
	}
	
	//////////////////////////////
	// Command to force IE to render 
	// background images correctly
	try {
		document.execCommand('BackgroundImageCache', false, true);
	} catch(e) {}
</script>
 <script type="text/javascript">
	// Create football gadget object
	var FBG=new FootballGadget();
	// Country list
	FBG.setCountries([
		{
			Name:"__MSG_Country_AR__",
			ID:"AR",
			DefaultLeague:104
		},
		{
			Name:"__MSG_Country_AU__",
			ID:"AU",
			DefaultLeague:98
		},
		{
			Name:"__MSG_Country_AT__",
			ID:"AT",
			DefaultLeague:94
		},
		{
			Name:"__MSG_Country_BE__",
			ID:"BE",
			DefaultLeague:18
		},
		{
			Name:"__MSG_Country_BR__",
			ID:"BR",
			DefaultLeague:106
		},
		{
			Name:"__MSG_Country_CN__",
			ID:"CN",
			DefaultLeague:309
		},
		{
			Name:"__MSG_Country_CZ__",
			ID:"CZ",
			DefaultLeague:30
		},
		{
			Name:"__MSG_Country_DK__",
			ID:"DK",
			DefaultLeague:1
		},
		{
			Name:"__MSG_Country_GB_England__",
			ID:"GB-__MSG_Country_GB_England__",
			DefaultLeague:4
		},
		{
			Name:"__MSG_Country_FI__",
			ID:"FI",
			DefaultLeague:108
		},
		{
			Name:"__MSG_Country_FR__",
			ID:"FR",
			DefaultLeague:15
		},
		{
			Name:"__MSG_Country_DE__",
			ID:"DE",
			DefaultLeague:9
		},
		{
			Name:"__MSG_Country_IE__",
			ID:"IE",
			DefaultLeague:102
		},
		{
			Name:"__MSG_Country_IT__",
			ID:"IT",
			DefaultLeague:7
		},
		{
			Name:"__MSG_Country_JP__",
			ID:"JP",
			DefaultLeague:227
		},
		{
			Name:"__MSG_Country_MX__",
			ID:"MX",
			DefaultLeague:219
		},
		{
			Name:"__MSG_Country_NL__",
			ID:"NL",
			DefaultLeague:20
		},
		{
			Name:"__MSG_Country_NO__",
			ID:"NO",
			DefaultLeague:17
		},
		{
			Name:"__MSG_Country_PT__",
			ID:"PT",
			DefaultLeague:14
		},
		{
			Name:"__MSG_Country_RU__",
			ID:"RU",
			DefaultLeague:109
		},
		{
			Name:"__MSG_Country_GB_Scotland__",
			ID:"GB-__MSG_Country_GB_Scotland__",
			DefaultLeague:22
		},
		{
			Name:"__MSG_Country_ES__",
			ID:"ES",
			DefaultLeague:13
		},
		{
			Name:"__MSG_Country_SE__",
			ID:"SE",
			DefaultLeague:74
		},
		{
			Name:"__MSG_Country_CH__",
			ID:"CH",
			DefaultLeague:96
		},
		{
			Name:"__MSG_Country_US__",
			ID:"US",
			DefaultLeague:118
		},
		{	
			Name:"__MSG_Country_GB_Wales__",
			ID:"GB-__MSG_Country_GB_Wales__",
			DefaultLeague:117
		}
	]);
	// Define league names overrides
	FBG.setCustomLeagueNames([
		{
			OriginalName:"Premier League",
			NewName:"Premiership"
		}
	]);
	// Define default view
	FBG.setDefaults({
		// Default country code
		Country:"__MSG_default_country_code__",
		// Sex defined by user preference default (UserPref male_female)
		Sex:"__UP_male_female__",
		// Default tab
		Tab:"ctrTabMatches"
	});
	// Start loading data before DOM is ready
	FBG.startGettingData();